package com.patent.controller;

import com.github.pagehelper.PageInfo;
import com.patent.common.DateUtil;
import com.patent.common.ExcelUtils;
import com.patent.common.JsonUtil;
import com.patent.common.PatentConstant;
import com.patent.common.ResultCode;
import com.patent.common.ResultData;
import com.patent.common.alipay.config.AlipayConfig;
import com.patent.common.alipay.sign.RSA;
import com.patent.common.alipay.util.AlipayCore;
import com.patent.domain.po.ChangeRecord;
import com.patent.domain.po.Patent;
import com.patent.domain.po.PatentOrder;
import com.patent.domain.po.PatentTransfer;
import com.patent.domain.po.PaymentRecord;
import com.patent.domain.po.RegisterRecord;
import com.patent.domain.vo.ExportParaVo;
import com.patent.domain.vo.PatentOrderVo;
import com.patent.domain.vo.PaymentAndPatentVo;
import com.patent.service.ChangeRecordService;
import com.patent.service.MonitorPatentService;
import com.patent.service.PatentOrderService;
import com.patent.service.PatentService;
import com.patent.service.PatentTransferService;
import com.patent.service.PaymentRecordService;
import com.patent.service.RegisterRecordService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/patent/")
public class PatentController {
	
	private static final Logger log = LoggerFactory.getLogger(PatentController.class);

	public static SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private PatentService         patentService;
	@Autowired
	private ChangeRecordService   changeRecordService;
	@Autowired
	private RegisterRecordService registerRecordService;
	@Autowired
	private PatentOrderService    patentOrderService;
	@Autowired
	private PaymentRecordService  paymentRecordService;
	@Autowired
	private PatentTransferService patenTransferService;
	@Autowired
	private MonitorPatentService  monitorPatentService;

	@Value("${ALIPAY_PRIVATE_KEY}")
	private String privateKey;
	@Value("${ALIPAY_PUBLIC_KEY}")
	private String JKalipayPublicKey;

	/**
	 *  通过专利名称、专利号、申请人、发明人查询专利信息
	 * @param applicationNo 专利号
	 * @param title  专利名称
	 * @param applicants 申请人(学校和个人)
	 * @param inventors 发明人
	 * @param flag 添加全部数据的监控标志 1
	 * @return
	 */
	@RequestMapping(value = "/getPatentInfoByConditions.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getPatentInfoByConditions(String userMobile,String applicationNo, String title, String applicants, String inventors,
	                                        @RequestParam(value="page", defaultValue="1") Integer page,
	                                        @RequestParam(value="rows",defaultValue="10") Integer rows,
	                                        String flag, HttpServletRequest request){
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(applicationNo)&&StringUtils.isBlank(title)&&
		            StringUtils.isBlank(applicants)&&StringUtils.isBlank(inventors)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("请至少输入专利号、专利名称、申请人、发明人的一项");
			return JsonUtil.write2JsonStr(resultData);
		}
		if(page != null && page <0){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("页码不能小于0");
			return JsonUtil.write2JsonStr(resultData);
		}
		if(rows != null && rows <0){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("页大小不能小于0");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			if(StringUtils.isNotBlank(title)){
				title = new String((request.getParameter("title")).getBytes("iso-8859-1"),"utf-8");
			}
			if(StringUtils.isNotBlank(applicants)){
				applicants = new String((request.getParameter("applicants")).getBytes("iso-8859-1"),"utf-8");
			}
			if(StringUtils.isNotBlank(inventors)){
				inventors = new String((request.getParameter("inventors")).getBytes("iso-8859-1"),"utf-8");
			}
			log.info("getPatentInfoByConditions param applicationNo:"+ applicationNo +"|title:"+ title +"|applicants:"+ applicants +"|inventors:"+ inventors
			         +"|page:"+ page +"|rows:"+ rows);
			PageInfo<Patent> patentList = patentService.getPatentInfoByConditions(userMobile, applicationNo, title, applicants, inventors, page, rows, flag);
			if(patentList == null || patentList.getTotal() == 0){
				//不关联监控表查
				List<Patent> patentList2 = patentService.getPatentInfoByConditions2(applicationNo, title, applicants, inventors, page, rows);
				if(patentList2 != null && patentList2.size() > 0){
					resultData.setCode(ResultCode.haveAdd.getCode());
					resultData.setMsg(ResultCode.haveAdd.getMessage());
					return JsonUtil.write2JsonStr(resultData);
				}
			}
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
			resultData.setResult(patentList);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController getPatentInfo:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 添加专利监控
	 * @param source :来源 1：钉钉 2：小程序
	 * @param userMobile 用户的手机号（标识登录人）
	 * @param id ：查出的专利主键(如果是页面选多个的话，用逗号隔开)
	 */
	@RequestMapping(value = "/addMonitorPatent.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addMonitorPatent(String source, String userMobile, String id){
		log.info("source:"+ source +"|userMobile:"+ userMobile +"|id:"+ id);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(id)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("请至少选择一个专利进行提交");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = patentService.addMonitorPatent(source, userMobile, id);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController addMonitorPatent:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 *  取消监控
	 * @param monitorId 监控专利表中的主键
	 * @return
	 */
	@RequestMapping(value = "/cancelMonitorPatent.do",  method = {RequestMethod.GET, RequestMethod.POST},produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String cancelMonitorPatent(String userMobile,String monitorId){
		log.info("monitorId:"+ monitorId);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(monitorId)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("monitorId is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = patentService.cancelMonitorPatent(monitorId);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController cancelMonitorPatent:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 首页
	 * 专利显示添加监控的数量
	 * 年费监控部分显示监控的专利权维持类型的专利数量
	 * @param userMobile 用户手机号
	 */
	@RequestMapping(value = "/queryIndexCount.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryIndexCount(String userMobile){
		log.info("queryIndexCount userMobile:"+userMobile);
		ResultData resultData = new ResultData();
		try {
			resultData = patentService.queryIndexCount(userMobile);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController queryIndexCount:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 查询各个专利对应的各个状态的专利信息
	 * @param userMobile 用户标识
	 * @param patentType 专利类型  见PatentConstant
	 * @param generalStatus 一般状态 见PatentConstant
	 */
	@RequestMapping(value = "/queryMonitorPatentInfo.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryMonitorPatentInfo(String userMobile,String patentType,String generalStatus, @RequestParam(value="page", defaultValue="1") Integer page,
	                                     @RequestParam(value="rows",defaultValue="10") Integer rows){
		log.info("queryMonitorPatentInfo userMobile:" + userMobile + "|patentType:"+ patentType + "|generalStatus:"+ generalStatus);
		ResultData resultData = new ResultData();
		if(StringUtils.isNotBlank(patentType)){
			if(StringUtils.isBlank(generalStatus)){
				resultData.setCode(ResultCode.paramError.getCode());
				resultData.setMsg("patentType和generalStatus必须同时传入值");
				return JsonUtil.write2JsonStr(resultData);
			}
		}
		try {
			resultData = patentService.queryMonitorPatentInfo(userMobile, patentType, generalStatus,page,rows);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController queryMonitorPatentInfo:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 *  年费监控
	 * @param userMobile 用户手机号
	 * @param patentType 年费类型
	 * @param applicationNo 专利号（通过专利号筛选的时候不传patentType）快速缴费的时候也不传patentType
	 */
	@RequestMapping(value = "/queryAnnualFee.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryAnnualFee(String userMobile,String patentType, @RequestParam(value="page", defaultValue="1") Integer page,
	                             @RequestParam(value="rows",defaultValue="10") Integer rows, String applicationNo){
		log.info("queryAnnualFee userMobile:"+userMobile +"|patentType:"+patentType + "|applicationNo:" + applicationNo);
		ResultData resultData = new ResultData();
		try {
			resultData = patentService.queryAnnualFee(userMobile, patentType, page, rows, applicationNo);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController queryAnnualFee:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 *  保存专利订单
	 * @param userMobile 用户手机号
	* @param list json串
	 * @return
	 */
	@RequestMapping(value = "/savePaymentRecord.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String savePaymentRecord(String userMobile, String list){
		log.info("savePaymentRecord userMobile: " + userMobile + " |list: " + list);
		List<PatentOrderVo> lists = JsonUtil.jsonToList(list, PatentOrderVo.class);
		ResultData resultData = new ResultData();
		if(list == null){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("list is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		Boolean flag = false ;
		for(PatentOrderVo orderVo : lists){
			Integer patentId = orderVo.getPatentId();
			String type = orderVo.getType();
			if(patentId == null || StringUtils.isBlank(type)){
				flag = true ;
				break;
			}
		}
		if(flag){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg(ResultCode.paramError.getMessage());
			return JsonUtil.write2JsonStr(resultData);
		}
		/*List<PatentOrderVo> list = new ArrayList<>();
		PatentOrderVo p1 = new PatentOrderVo();
		p1.setPatentId(7);
		p1.setType("发明专利第5年年费");
		list.add(p1);
		PatentOrderVo p2 = new PatentOrderVo();
		p2.setPatentId(25);
		p2.setType("发明专利第5年年费");
		list.add(p2);*/
		try {
			resultData = patentService.savePaymentRecord(userMobile, lists);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController savePaymentRecord: " + JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 查询代缴记录
	 * @param userMobile 用户手机号
	 * @return
	 */
	@RequestMapping(value = "/queryPaymentRecord.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryPaymentRecord(String userMobile,@RequestParam(value="page", defaultValue="1") Integer page,
	                                 @RequestParam(value="rows",defaultValue="10") Integer rows){
		log.info("queryPaymentRecord userMobile:"+userMobile);
		ResultData resultData = new ResultData();
		try {
			resultData = patentService.queryPaymentRecord(userMobile,page,rows);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("queryPaymentRecord result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 导出代缴记录
	 * @param userMobile
	 */
	@RequestMapping(value = "/exportPaymentRecord.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String exportPaymentRecord(String userMobile, HttpServletResponse response, HttpServletRequest request,@RequestParam(value="page", defaultValue="1") Integer page,
	                                @RequestParam(value="rows",defaultValue="100000") Integer rows){
		String fileName = "";
		ResultData resultData = new ResultData();
		//查询data
		try {
			ExportParaVo paravo = new ExportParaVo();
			resultData = patentService.queryPaymentRecord(userMobile,page,rows);
			if(resultData != null && ResultCode.success.getCode().equals(resultData.getCode())){
				List<PaymentAndPatentVo> list = (List<PaymentAndPatentVo>) resultData.getResult();
				for(PaymentAndPatentVo paymentAndPatentVo : list){
					Date date = paymentAndPatentVo.getPaidTime();
					if(date != null){
						String dateStr = DateUtil.formatDateToString(date, yyyyMMddHHmmss);
						paymentAndPatentVo.setPaymentDateStr(dateStr);
					}
					Date operatorDate =  paymentAndPatentVo.getOperatorDate();
					if(operatorDate != null){
						String operatorDateStr = DateUtil.formatDateToString(operatorDate, yyyyMMddHHmmss);
						paymentAndPatentVo.setOperatorDateStr(operatorDateStr);
					}
				}
				paravo.setData(list);
				paravo.setFileKey("paymentRecord");
				paravo.setDefaultFileName(userMobile+":代缴记录");
				fileName = ExcelUtils.exportExcel(paravo, request, response);
				fileName = "http://p6wn0pyzn.bkt.clouddn.com/" + fileName;
				resultData.setCode(ResultCode.success.getCode());
				resultData.setMsg(ResultCode.success.getMessage());
				resultData.setResult(fileName);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error("导出代缴记录失败："+e.getMessage());
		}
		log.info("exportPaymentRecord result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 专利号查专利信息
	 */
	@RequestMapping(value = "/queryPatentInfo.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryPatentInfo(String userMobile,String applicationNo){
		log.info("queryPatentInfo userMobile:"+userMobile +"|applicationNo:"+applicationNo);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(applicationNo)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("applicationNo is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = patentService.queryPatentInfo(userMobile,applicationNo);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("queryPatentInfo result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 *  添加著录项变更
	 * @param userMobile 手机号
	 * @param patentId  专利主键
	 * @param applicantsNew 申请人变更后的信息
	 * @param inventorsNew 发明人变更后的信息
	 * @return
	 */
	@RequestMapping(value = "/addChangeInfo.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addChangeInfo(String userMobile, String patentId, String applicantsNew, String inventorsNew){
		log.info("addChangeInfo param userMobile:"+userMobile +"|patentId:"+patentId +"|applicantsNew:"+applicantsNew +"|inventorsNew:"+inventorsNew);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(patentId)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("patentId is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = changeRecordService.addChangeInfo(userMobile,patentId, applicantsNew, inventorsNew);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("addChangeInfo result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 专利号查专利信息判断专利状态是否是专利权维持的
	 * true 是
	 * false 不是
	 */
	@RequestMapping(value = "/checkPatentStatu.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String checkPatentStatu(String userMobile,String applicationNo){
		log.info("checkPatentStatu userMobile:"+userMobile +"|applicationNo:"+applicationNo);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(applicationNo)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("applicationNo is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = patentService.checkPatentStatu(userMobile,applicationNo);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("checkPatentStatu result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 添加登记薄副本
	 * @param userMobile
	 * @param patentId
	 * @param registerNum  副本数量
	 * @return
	 */
	@RequestMapping(value = "/addRegisterInfo.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addRegisterInfo(String userMobile, String patentId,
	                              @RequestParam(value="registerNum", defaultValue="1")Integer registerNum){
		log.info("addRegisterInfo param userMobile:"+userMobile +"|patentId:"+patentId +"|registerNum:"+registerNum);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(patentId)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("patentId is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = registerRecordService.addRegisterInfo(userMobile,patentId, registerNum);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("addRegisterInfo result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 查著录项变更的记录
	 * queryFlag ： 空：历史订单  1：快速缴费（未支付的）
	 */
	@RequestMapping(value = "/queryChangeInfo.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryChangeInfo(String userMobile, String queryFlag, @RequestParam(value="page", defaultValue="1") Integer page,
	                              @RequestParam(value="rows",defaultValue="10") Integer rows){
		ResultData resultData = new ResultData();
		try {
			resultData = changeRecordService.queryChangeInfo(userMobile, queryFlag, page, rows);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("queryChangeInfo result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 查登记录副本的历史操作
	 * queryFlag ： 空：历史订单  1：快速缴费（未支付的）
	 */
	@RequestMapping(value = "/queryRegisterInfo.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryRegisterInfo(String userMobile, String queryFlag, @RequestParam(value="page", defaultValue="1") Integer page,
	                                @RequestParam(value="rows",defaultValue="10") Integer rows){
		ResultData resultData = new ResultData();
		try {
			resultData = registerRecordService.queryRegisterInfo(userMobile, queryFlag, page, rows);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("queryRegisterInfo result:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 支付宝签名（专利或著录项变更或登记录副本）
	 * @param id ：订单orderNo
	 * @param signFlag : 签名类型 1：著录项变更  2：登记录副本 3：专利
	 */
	@RequestMapping(value = "/assembleSign.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String assembleSign(String id, Integer signFlag){
		ResultData resultData = new ResultData();
		if(id == null){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("id is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		if(signFlag == null){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("signFlag is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			String finalString = "";
			ChangeRecord changeRecord = null;
			RegisterRecord registerRecord = null;
			PatentOrder patentOrder = null;
			if(PatentConstant.CHANGE_OF_DESCRIPTION.equals(signFlag)){//著录项变更
				changeRecord = changeRecordService.queryByOrderNo(id);
				if(changeRecord != null){
					//String orderNum, String subject, String body, BigDecimal total_fee, String notify_url
					//body = "{\"patentId\":\""+changeRecord.getPatentId()+"\",\"official_amount\":\""+changeRecord.getOfficialAmount()+"\",\"agent_amount\":\""+changeRecord.getAgentAmount()+"\"}";   //商品详情
					finalString = getAlipaySignStr(changeRecord.getOrderNo().toString(), "著录项变更", "test",
					                               changeRecord.getOrderAmount(), AlipayConfig.notify_url_change);
					}
			}else if(PatentConstant.REGISTER.equals(signFlag)){//登记薄副本
				registerRecord = registerRecordService.queryByOrderNo(id);
				log.info("registerRecord:" + JsonUtil.write2JsonStr(registerRecord));
				if(registerRecord != null){
					//body = "{\"register_num\":\""+registerRecord.getRegisterNum()+"\",\"official_amount\":\""+registerRecord.getOfficialAmount()+"\",\"agent_amount\":\""+registerRecord.getAgentAmount()+"\"}";
					finalString = getAlipaySignStr(registerRecord.getOrderNo().toString(), "登记薄副本", "test",
					                               registerRecord.getOrderAmount(), AlipayConfig.notify_url_register);
					}
			}else if(PatentConstant.PATENT.equals(signFlag)){//专利
				patentOrder = patentOrderService.queryByOrderNo(id);
				if(patentOrder != null){
					//body = "{\"register_num\":\""+registerRecord.getRegisterNum()+"\",\"official_amount\":\""+registerRecord.getOfficialAmount()+"\",\"agent_amount\":\""+registerRecord.getAgentAmount()+"\"}";
					finalString = getAlipaySignStr(patentOrder.getOrderNo().toString(), "专利代缴费用", "test",
					                               patentOrder.getPayAmount(), AlipayConfig.notify_url_patent);
				}
			}
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
			resultData.setResult(finalString);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取alipay支付签名失败："+e.getMessage());
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
		}
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 支付宝支付参数
	 * @param orderNum 订单号
	 * @param subject 商品名称
	 * @param body 商品详情
	 * @param total_fee 支付费用
	 * @param notify_url 回调地址
	 */
	private String getAlipaySignStr(String orderNum, String subject, String body, Double total_fee, String notify_url){
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("partner", "\"" + AlipayConfig.partner + "\"");
		paramMap.put("seller_id", "\"" + AlipayConfig.seller + "\"");
		paramMap.put("out_trade_no", "\"" + orderNum + "\"");
		paramMap.put("subject", "\"" + subject + "\"");
		paramMap.put("body", "\"" + body + "\"");
		paramMap.put("total_fee", "\"" + total_fee + "\"");
		paramMap.put("service", "\"" + AlipayConfig.mobile_service + "\"");
		paramMap.put("payment_type", "\"" + "1" + "\"");
		paramMap.put("_input_charset", "\"" + "utf-8" + "\"");
		//paramMap.put("it_b_pay", "\"" + AlipayConfig.it_b_pay + "\"");
		paramMap.put("notify_url", "\"" + notify_url + "\"");

		// 2.参数map转string
		String paramStr = AlipayCore.createLinkString(paramMap);
		log.info("getAlipaySignStr paramStr:"+paramStr);

		// 3.签名
		String signStr = RSA.sign(paramStr, AlipayConfig.private_key_pkcs8, "utf-8");
		log.info("getAlipaySignStr 未编码 signStr:"+ signStr);

		// 4.签名URLEncoder编码
		try {
			signStr = URLEncoder.encode(signStr, "UTF-8");
			log.info("getAlipaySignStr 编码后 signStr:"+ signStr);
		} catch (UnsupportedEncodingException e) {
			log.error("getAlipaySignStr编码失败："+e.getMessage());
			return null;
		}

		// 5.汇总参数string
		String retrnStr = paramStr + "&sign=\"" + signStr + "\"&sign_type=\"" + AlipayConfig.sign_type+ "\"";
		log.info("getAlipaySignStr retrnStr:"+retrnStr);
		return retrnStr;
	}

	/**
	 * 支付宝回调处理(著录项变更)
	 */
	/*@RequestMapping(value = "/dealPayResponseForChange.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dealPayResponseForChange(HttpServletRequest request, HttpServletResponse response){
		ResultData resultData = new ResultData();
		log.info("支付宝服务器异步通知---------");
		Map<String,String> requestParams = new HashMap<String,String>();
		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements()) {
			String nms = en.nextElement().toString();
			requestParams.put(nms, request.getParameter(nms).trim());
		}
		try {
			boolean signVerified = AlipayNotify.verify(requestParams);
			//boolean signVerified = AlipaySignature.rsaCheckV1(requestParams, JKalipayPublicKey, "utf-8","RSA");
			if(signVerified){ //验签成功后再操作
				//先拿到通知的交易状态
				String trade_status = request.getParameter("trade_status");
				log.info("交易状态-----"+trade_status);
				if(trade_status.equals("TRADE_SUCCESS")) {
					*//**
					 *支付成功之后的业务处理
					 *//*
					String notify_time = request.getParameter("notify_time");
					String trade_no = request.getParameter("trade_no");
					String total_amount = request.getParameter("total_amount");
					String out_trade_no = request.getParameter("out_trade_no");
					String seller_id = request.getParameter("seller_id");
					log.info("支付成功各个参数-----"+"notify_time："+notify_time+"trade_no："+trade_no+"total_amount："+total_amount+"out_trade_no："+out_trade_no);
					ChangeRecord changeRecord = changeRecordService.selectByPrimaryKey(Integer.parseInt(out_trade_no));
					// 服务器本地验证订单合法性(订单金额一致，且是未支付完成的)
					if (changeRecord !=null && changeRecord.getOrderAmount().equals(total_amount)
					    && changeRecord.getOrderState() != PatentConstant.PAY_SUCCESS
					    && AlipayConfig.seller.equals(seller_id)) {
						log.info("修改著录项变更start");
						//更新订单表
						changeRecord.setTransNo(trade_no);					// 支付渠道交易流水
						changeRecord.setPaidTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(notify_time) );		// 订单完成时间
						changeRecord.setOrderState(2); 							// 支付成功
						changeRecordService.updateByPrimaryKeySelective(changeRecord);
						resultData.setCode(ResultCode.success.getCode());
						resultData.setMsg(ResultCode.success.getMessage());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("解密失败："+e.getMessage());
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
		}
		return JsonUtil.write2JsonStr(resultData);
	}*/

	/**
	 * 支付宝回调处理(登记录副本)
	 */
	/*@RequestMapping(value = "/dealPayResponseForRegister.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dealPayResponseForRegister(HttpServletRequest request, HttpServletResponse response){
		ResultData resultData = new ResultData();
		log.info("支付宝服务器异步通知---------");
		Map<String,String> requestParams = new HashMap<String,String>();
		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements()) {
			String nms = en.nextElement().toString();
			requestParams.put(nms, request.getParameter(nms).trim());
		}
		try {
			boolean signVerified = AlipayNotify.verify(requestParams);
			//boolean signVerified = AlipaySignature.rsaCheckV1(requestParams, JKalipayPublicKey, "utf-8","RSA");
			if(signVerified){ //验签成功后再操作
				//先拿到通知的交易状态
				String trade_status = request.getParameter("trade_status");
				log.info("交易状态-----"+trade_status);
				if(trade_status.equals(AliPayStatusEnum.SUCCESS.getValue())) {
					*//**
					 *支付成功之后的业务处理
					 *//*
					String notify_time = request.getParameter("notify_time");
					String trade_no = request.getParameter("trade_no");
					String total_amount = request.getParameter("total_amount");
					String out_trade_no = request.getParameter("out_trade_no");
					String seller_id = request.getParameter("seller_id");
					log.info("支付成功各个参数-----"+"notify_time："+notify_time+"trade_no："+trade_no+"total_amount："+total_amount+"out_trade_no："+out_trade_no);
					RegisterRecord registerRecord = registerRecordService.selectByPrimaryKey(Integer.parseInt(out_trade_no));
					// 服务器本地验证订单合法性(订单金额一致，且是未支付完成的)
					if (registerRecord!=null && registerRecord.getOrderAmount().equals(total_amount)
					        && registerRecord.getOrderState() != PatentConstant.PAY_SUCCESS
							&& AlipayConfig.seller.equals(seller_id)) {
						log.info("修改登记录副本表start");
						//更新订单表
						registerRecord.setTransNo(trade_no);					// 支付渠道交易流水
						registerRecord.setPaidTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(notify_time) );		// 订单完成时间
						registerRecord.setOrderState(2); 							// 支付成功
						registerRecordService.updateByPrimaryKeySelective(registerRecord);
						resultData.setCode(ResultCode.success.getCode());
						resultData.setMsg(ResultCode.success.getMessage());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("解密失败："+e.getMessage());
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
		}
		return JsonUtil.write2JsonStr(resultData);
	}*/



	/**
	 *  手动添加专利监控
	 * @param source :来源 1：钉钉 2：小程序
	 * @param userMobile 用户的手机号（标识登录人）
	 * @param applicationNo 专利号（数据库没有，需手动添加的）
	 */
	@RequestMapping(value = "/addPatentByManual.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addPatentByManual(String source, String userMobile, String applicationNo){
		log.info("source:" + source + "|userMobile:" + userMobile + "|applicationNo:" + applicationNo);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(source)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("source is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		if(StringUtils.isBlank(applicationNo)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("applicationNo is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		try {
			resultData = patentService.addPatentByManual(source, userMobile, applicationNo);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController addPatentByManual:"+JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 处理支付宝的同步通知
	 * @param signFlag 1：著录项变更  2：登记录副本 3：专利
	 * @param orderNo 订单号
	 * @param orderAmount 订单金额
	 * @param sellerId 支付宝账号
	 */
	@RequestMapping(value = "/dealAlipayResponse.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dealAlipayResponse(Integer signFlag, String orderNo, Double orderAmount, String sellerId){
		log.info("dealAlipayResponse signFlag:" + signFlag + "||orderNo:" + orderNo
		         + "||orderAmount:" + orderAmount + "||sellerId:" + sellerId);
		ResultData resultData = new ResultData();
		//验签
		/*Map<String, String> params = changeResultToMap(result);
		if(params.get("sign") != null) {
			String sign = (String) params.get("sign");
			boolean isSign = AlipayNotify.getSignVeryfy(params, sign);
			if (isSign && params.get("success").equals("true")) {
			}
		}*/
		//修改数据库状态
		if(signFlag != null && StringUtils.isNotBlank(orderNo)){
			if(PatentConstant.CHANGE_OF_DESCRIPTION.equals(signFlag)){
				ChangeRecord changeRecord = changeRecordService.queryByOrderNo(orderNo);
				// 服务器本地验证订单合法性(订单金额一致，且是未支付完成的)
				if (changeRecord != null && changeRecord.getOrderAmount().equals(orderAmount)
				    && changeRecord.getOrderState() != PatentConstant.PAY_SUCCESS
				    && AlipayConfig.seller.equals(sellerId)) {
					log.info("修改著录项变更start");
					//changeRecord.setTransNo(trade_no);					// 支付渠道交易流水
					changeRecord.setPaidTime(new Date());		// 订单完成时间
					changeRecord.setUpdateDate(new Date());
					changeRecord.setOrderState(PatentConstant.PAY_SUCCESS); 							// 支付成功
					try {
						changeRecordService.updateRecordC(changeRecord);
						resultData.setCode(ResultCode.success.getCode());
						resultData.setMsg(ResultCode.success.getMessage());
					} catch (Exception e) {
						e.printStackTrace();
						resultData.setCode(ResultCode.otherError.getCode());
						resultData.setMsg(ResultCode.otherError.getMessage());
					}
				}else{
					resultData.setCode(ResultCode.paramError.getCode());
					resultData.setMsg(ResultCode.paramError.getMessage());
				}
			}else if(PatentConstant.REGISTER.equals(signFlag)){
				RegisterRecord registerRecord = registerRecordService.queryByOrderNo(orderNo);
				// 服务器本地验证订单合法性(订单金额一致，且是未支付完成的)
				if (registerRecord != null && registerRecord.getOrderAmount().equals(orderAmount)
				    && registerRecord.getOrderState() != PatentConstant.PAY_SUCCESS
				    && AlipayConfig.seller.equals(sellerId)) {
					log.info("修改登记录副本表start");
					//registerRecord.setTransNo(trade_no);
					registerRecord.setPaidTime(new Date());
					registerRecord.setUpdateDate(new Date());
					registerRecord.setOrderState(PatentConstant.PAY_SUCCESS);
					try {
						registerRecordService.updateRecordR(registerRecord);
						resultData.setCode(ResultCode.success.getCode());
						resultData.setMsg(ResultCode.success.getMessage());
					} catch (Exception e) {
						e.printStackTrace();
						resultData.setCode(ResultCode.otherError.getCode());
						resultData.setMsg(ResultCode.otherError.getMessage());
					}
					resultData.setCode(ResultCode.success.getCode());
					resultData.setMsg(ResultCode.success.getMessage());
				}else{
					resultData.setCode(ResultCode.paramError.getCode());
					resultData.setMsg(ResultCode.paramError.getMessage());
				}
			}else if(PatentConstant.PATENT.equals(signFlag)){
				PatentOrder patentOrder = patentOrderService.queryByOrderNo(orderNo);
				if (patentOrder!=null && patentOrder.getPayAmount().equals(orderAmount)
				    && patentOrder.getOrderState() != PatentConstant.PAY_SUCCESS
				    && AlipayConfig.seller.equals(sellerId)) {
					log.info("修改专利订单主表start");
					//patentOrder.setTransNo(trade_no);
					patentOrder.setPaidTime(new Date());
					patentOrder.setUpdateDate(new Date());
					patentOrder.setOrderState(PatentConstant.PAY_SUCCESS);
					try {
						patentOrderService.updateRecordP(patentOrder);
						log.info("修改专利订单子表start");
						String pId = patentOrder.getPaymentRecordId();
						if(StringUtils.isNotBlank(pId)){
							String pIdArray[] = pId.split(",");
							if(pIdArray != null && pIdArray.length > 0){
								for(int i = 0;i <pIdArray.length;i++){
									Integer id = Integer.parseInt(pIdArray[i]);
									PaymentRecord record = new PaymentRecord();
									record.setId(id);
									record.setPaidTime(new Date());
									record.setUpdateDate(new Date());
									record.setOrderState(PatentConstant.PAY_SUCCESS);
									paymentRecordService.updateByPrimaryKeySelective(record);
								}
							}
						}
						resultData.setCode(ResultCode.success.getCode());
						resultData.setMsg(ResultCode.success.getMessage());
					} catch (Exception e) {
						e.printStackTrace();
						resultData.setCode(ResultCode.otherError.getCode());
						resultData.setMsg(ResultCode.otherError.getMessage());
					}
				}else{
					resultData.setCode(ResultCode.paramError.getCode());
					resultData.setMsg(ResultCode.paramError.getMessage());
				}
			}
		}
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 将同步通知结果转换为map
	 */
	private Map<String, String> changeResultToMap(String result){
		Map<String, String> map = new HashMap<String, String>();
		if(StringUtils.isNotBlank(result)){
			String resultArray[] = result.split("&");
			if(resultArray != null && resultArray.length > 0){
				for(int i = 0; i < resultArray.length; i++){
					String arr[] = resultArray[i].split("=");
					if(arr != null && arr.length > 0){
						map.put(arr[0], arr[1].substring(1,arr[1].length()-1));
					}
				}
			}
		}
		return map;
	}

	/**
	 * 添加专利转让
	 */
	@RequestMapping(value = "/addPatentTransfer.do", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addPatentTransfer(String userMobile, String applicationNo, String partner, Integer cooperationWay, Double cost, Integer transferWay){
		log.info("userMobile:" + userMobile + "|partner:"+ partner + "|cooperationWay:"+ cooperationWay
		         + "|cost:"+ cost + "|transferWay:"+ transferWay + "|applicationNo:"+ applicationNo);
		ResultData resultData = new ResultData();
		if(StringUtils.isBlank(applicationNo)){
			resultData.setCode(ResultCode.paramError.getCode());
			resultData.setMsg("applicationNo is null");
			return JsonUtil.write2JsonStr(resultData);
		}
		PatentTransfer patentTransfer = new PatentTransfer();
		patentTransfer.setUserMobile(userMobile);
		patentTransfer.setPartner(partner);
		patentTransfer.setCooperationWay(cooperationWay);
		patentTransfer.setCost(cost);
		patentTransfer.setTransferWay(transferWay);
		patentTransfer.setApplicationNo(applicationNo);
		try {
			patenTransferService.addPatentTransfer(patentTransfer);
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController addPatentTransfer:" + JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

	/**
	 * 查询添加的专利
	 * @param userMobile
	 * @return
	 */
	@RequestMapping(value = "/queryAddPatent.do", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryAddPatent(String userMobile,@RequestParam(value="page", defaultValue="1") Integer page,
	                             @RequestParam(value="rows",defaultValue="10") Integer rows){
		ResultData resultData = new ResultData();
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("userMobile", userMobile);
			map.put("page",(page-1)*rows);
			map.put("rows",rows);
			List<Patent> list = monitorPatentService.queryMonitorPatentInfo(map);
			resultData.setCode(ResultCode.success.getCode());
			resultData.setMsg(ResultCode.success.getMessage());
			resultData.setResult(list);
		} catch (Exception e) {
			resultData.setCode(ResultCode.otherError.getCode());
			resultData.setMsg(ResultCode.otherError.getMessage());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		log.info("PatentController queryAddPatent:" + JsonUtil.write2JsonStr(resultData));
		return JsonUtil.write2JsonStr(resultData);
	}

}
